package org.jin.samples.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jin.samples.model.vo.ExamUserVO;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {
	
	/*
	 * 当Interceptor中的preHandle方法返回true时才执行，该方法在整个请求完成之后，也就是已经视图渲染了
	 * 才执行。主要用于清理资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("----afterCompletion----");
	}

	/*
	 *当Interceptor中的preHandle方法返回true时才执行，是在controller调用之后执行的，但会在dispatcherServlet
	 *进行视图渲染前调用，所以该方法可以在modelAndView进行操作 
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("----postHandle----");
	}

	/*
	 *是在controller处理之前调用的。拦截器是链式的，所有的 Interceptor中的preHandle方法都会在
	 *controller处理之前调用的，链式是可中断的，当preHandle方法返回false时整个请求就结束了
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		HttpSession session=request.getSession();
		ExamUserVO examUseVO = (ExamUserVO) session.getAttribute("examUser");
		if(examUseVO != null){
			return true;
		}else{
			response.sendRedirect(request.getContextPath()+"/login");
			System.out.println("request.getContextPath()="+request.getContextPath());
		}
		System.out.println("*********request.getContextPath()*********");
		return false;
	}
}
